package com.cowealth.platform.common.db.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cowealth.platform.common.db.annotation.BaseDOAutoFill;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义创建时间和更新时间的填充规则
 *
 * https://blog.csdn.net/qq_33691413/article/details/105538479
 *
 * @author : skycdm
 * @version : 1.0.0
 * @date : 2021/1/19 16:45
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        //根据属性名字设置要填充的值
        Class<?> originalClass = metaObject.getOriginalObject().getClass();
        BaseDOAutoFill autoFill = originalClass.getAnnotation(BaseDOAutoFill.class);
        //TODO 字段添加了自动填充的注解后，初始化会强制添加插入字段，不判断空，导致inser into a (a) value (null) 报错
//        if (autoFill != null && autoFill.value()) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
//        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Class<?> originalClass = null;
        if (metaObject.getObjectWrapper().hasGetter("param1")) {
            originalClass = metaObject.getObjectWrapper().getGetterType("param1");
        } else if (metaObject.getObjectWrapper().hasGetter("et")) {
            originalClass = metaObject.getObjectWrapper().getGetterType("et");
        } else {
            return;
        }
        BaseDOAutoFill autoFill = originalClass.getAnnotation(BaseDOAutoFill.class);
//        if (autoFill != null && autoFill.value()) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
//        }


    }
}
